#! /bin/bash
#系统更新
 apt update -y
 echo -e "系统更新成功"
 sleep 3 
 #  证书机构
 apt install easy-rsa openssl -y 
 echo -e "证书安装成功"
 sleep 3 
 #生成证书环境变量
 mkdir /opt/easy-rsa
 echo -e "创建目录成功"
 sleep 3
 cp -a /usr/share/easy-rsa/* /opt/easy-rsa/
 sleep 3
 #配置文件
 cat >> /opt/easy-rsa/vars <<EOF
export KEY_COUNTRY="CN"   
export KEY_PROVINCE="SD"   
export KEY_CITY="QingDao"   
export KEY_ORG="xiaolu"     
export KEY_EMAIL="349281613@qq.com"    
EOF
sleep 2
echo -e "配置文件生成成功"
#创建pki 目录
cd /opt/easy-rsa/
./easyrsa init-pki
echo -e "创建pki目录成功"
sleep 3
echo -e "创建根证书 先输入密码xiaolu  在回车键"
./easyrsa build-ca nopass
echo -e "创建根证书成功"
sleep 3
echo -e "创建服务端证书以及密钥 直接回车建 "
./easyrsa gen-req server nopass
echo -e "创建证书和私钥成功"
sleep 3
echo -e "证书签名 先输入yes  在输入xiaolu"
./easyrsa sign server server 
echo -e "服务端签名成功"
./easyrsa gen-dh
echo -e "diffie-hellman算法成功"
sleep 3 
echo -e "开始创建客户端证书以及私钥 直接回车建"
./easyrsa gen-req client nopass
echo -e "先输入yes 输入xiaolu"
./easyrsa sign client client
echo -e "客户端证书签名成功"
sleep 3 
ls /opt/easy-rsa/pki/ca.crt
ls /opt/easy-rsa/pki/reqs/server.req
ls /opt/easy-rsa/pki/private/server.key
ls /opt/easy-rsa/pki/issued/server.crt
ls /opt/easy-rsa/pki/dh.pem
ls /opt/easy-rsa/pki/reqs/client.req
ls /opt/easy-rsa/pki/private/client.key
ls /opt/easy-rsa/pki/issued/client.crt
ehco -e "证书正常"
#安装openvpn服务端
apt install openvpn -y 
#创建日志目录
mkdir /etc/openvpn/logs -p
#添加证书
\cp /opt/easy-rsa/pki/ca.crt /etc/openvpn/server/
\cp /opt/easy-rsa/pki/issued/server.crt /etc/openvpn/server/
\cp /opt/easy-rsa/pki/private/server.key /etc/openvpn/server/
\cp /opt/easy-rsa/pki/dh.pem /etc/openvpn/server/
\cp /opt/easy-rsa/pki/ca.crt /etc/openvpn/client/
\cp /opt/easy-rsa/pki/private/client.key /etc/openvpn/client/
\cp /opt/easy-rsa/pki/issued/client.crt /etc/openvpn/client/
echo -e "添加证书成功"
#配置server 文件
cat >/etc/openvpn/server.conf <<EOF
port 1194

proto udp
dev tun
ca /etc/openvpn/server/ca.crt
cert /etc/openvpn/server/server.crt
key /etc/openvpn/server/server.key
dh /etc/openvpn/server/dh.pem
server 10.8.0.0 255.255.255.0
push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 8.8.8.8"
push "dhcp-option DNS 114.114.114.114"
ifconfig-pool-persist /etc/openvpn/logs/ipp.txt
keepalive 10 120
max-clients 100
status /etc/openvpn/logs/openvpn-status.log
verb 3
client-to-client
log /etc/openvpn/logs/openvpn.log
persist-key
persist-tun
duplicate-cn
EOF
#系统内核转发
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
sysctl -p
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo echo -e "ip内核转发成功共享上网成功"
#开机并且启动
systemctl enable openvpn.service
systemctl start  openvpn.service
mkdir /home/ubuntu/xiaolu -p
cp -a /etc/openvpn/client/* /home/ubuntu/xiaolu

sleep 3
echo -e "
client
dev tun
proto udp
remote 10.0.0.61 1194
resolv-retry infinite
nobind
ca ca.crt
cert client.crt
key client.key
verb 3
persist-key
">>/home/ubuntu/xiaolu/xiaolu.ovpn
sleep 3
tar -zcvf /home/ubuntu/xiaolu.tar.gz /home/ubuntu/xiaolu
echo -e "架设成功"
